package com.digdes.calendar.gwt.client.widget;

import com.digdes.calendar.gwt.client.dto.PlaceDTOImpl;
import com.digdes.calendar.gwt.client.dto.UserDTOImpl;
import com.digdes.calendar.gwt.client.service.CalendarService;
import com.digdes.calendar.gwt.client.service.CalendarServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * User: Dmitry
 * Date: 15.05.12
 * Time: 16:42
 */
public class ChoiceDialog extends DialogBox {
    final ListBox choicesListBox = new ListBox();
    VerticalPanel vPanel = new VerticalPanel();
    List<Object> records = new ArrayList<Object>(0);
    List<Object> choices = new ArrayList<Object>(0);
    List<String> choicesList = new ArrayList<String>(0);
    // supChoiceList нужно для того, чтобы по выделенному объеку в choiceListBox найти
    // правильную запись в choices
    List<Integer> supChoiceList = new ArrayList<Integer>(0);
    Plan scheduler;
    private final CalendarServiceAsync calendarservice = GWT.create(CalendarService.class);
    TextBox textbox = new TextBox();

    //  choicesPlace.clear();
    public ChoiceDialog(Plan scheduler) {
        this.setText("Пожалуйста выберите запись.");
        choicesListBox.setWidth("300px");
        choicesListBox.setVisibleItemCount(3);

        this.scheduler = scheduler;
        textbox.addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent keyPressEvent) {
                choicesListBox.setVisible(true);
                String text = textbox.getValue();
                choicesListBox.clear();
                supChoiceList.clear();
                if (text.length() != 0) {
                    for (int i = 0;i<choicesList.size();i++) {

                        if (choicesList.get(i).regionMatches(true, 0, text, 0, text.length())) {
                            choicesListBox.addItem(choicesList.get(i));
                            supChoiceList.add(i);
                            //break;
                        }
                        choicesListBox.setSelectedIndex(0);
                    }
                }
            }
        });
        choicesListBox.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                textbox.setText(choicesListBox.getValue(choicesListBox.getSelectedIndex()));
                choicesListBox.setVisible(false);
            }
        });
        Button okButton = new Button("OK");
        okButton.addClickHandler(clickSelect);
       /* okButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                ChoiceDialog.this.hide();
            }
        });*/

        vPanel.add(textbox);
        vPanel.add(choicesListBox);
        vPanel.add(okButton);

        this.setWidget(vPanel);
    }

    public void showDialog(Character who) {
        choices.clear();
        choicesList.clear();
        choicesListBox.clear();
        textbox.setText("");
        choicesListBox.setVisible(false);
        // Если была передана u то диалог будет строиться для выбора участника события, если p то для выбора места.
        if (who == 'u') {
            calendarservice.getUsers(new AsyncCallback<Set<UserDTOImpl>>() {
                public void onFailure(Throwable caught) {

                }

                public void onSuccess(Set<UserDTOImpl> result) {
                    for (UserDTOImpl user : result) {
                        StringBuilder fullName = new StringBuilder();
                        if (user.getSurname()!= null) {
                        fullName.append(user.getSurname());
                        fullName.append(" ");}
                        if (user.getName()!= null) {
                        fullName.append(user.getName());}
                        fullName.append(" ");
                        if (user.getPatronymic()!= null)
                        fullName.append(user.getPatronymic());

                        choicesList.add(fullName.toString());
                        choices.add(user);
                    }
                }
            });

        } else {
            calendarservice.getAllPlace(new AsyncCallback<Set<PlaceDTOImpl>>() {
                public void onFailure(Throwable caught) {

                }

                public void onSuccess(Set<PlaceDTOImpl> result) {
                    for (PlaceDTOImpl place : result) {
                        choicesList.add(place.getAddress());
                        choices.add(place);
                    }

                }
            });
        }

        this.center();
    }

    ClickHandler clickSelect = new ClickHandler() {
        public void onClick(ClickEvent clickEvent) {
            Object newRecord = choices.get(supChoiceList.get(choicesListBox.getSelectedIndex()));
            if (!records.contains(newRecord)) {
                records.add(newRecord);
                scheduler.addRecord(newRecord,scheduler.panel.getCurLine()-1);
                scheduler.panel.setCurLine(scheduler.panel.getCurLine() + 1);
                if ((scheduler.panel.getCurLine()) > scheduler.panel.getVsize()) scheduler.addLine();

            }
            ChoiceDialog.this.hide();
        }
    };

    public List<Object> getRecords() {
        return this.records;
    }

    public void setRecordsPlace(List<Object> records) {
        this.records = records;
    }

    public List<Object> getChoicesPlace() {
        return this.choices;
    }

    public ListBox getChoicesListBox() {
        return this.choicesListBox;
    }
    
}